package zozopo.background.operator;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.json.JSONException;
import org.json.JSONObject;

import zozopo.background.operator.operations.LimitedTB;
import zozopo.background.operator.operations.OperatorOS;
import zozopo.background.operator.operations.OperatorTB;
import zozopo.background.operator.operations.OperatorlimitedOS;
import zozopo.background.operator.operations.OperatorlimitedTB;
import zozopo.background.operator.operations.QQOperatorOS;
import zozopo.background.operator.operations.QQOperatorTB;
import zozopo.log.operations.OperatorLoginLogOS;
import zozopo.log.operations.OperatorLoginLogTB;
import zozopo.operations.comm.DictionaryTB;
import zozopo.user.operations.UserTB;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

public class QQLoginAction extends ActionSupport implements Action,SessionAware,ServletRequestAware,ServletResponseAware{
	
	HttpServletRequest request;
	HttpServletResponse response;
	private Map<Object, Object> session;
	private static final String webSitUrl = "www.zozopo.com";
	private static final String APP_ID="100231532";
	private static final String KEY = "7e553a946bea3ff594ea3392adfa69e7";
	
	//传入参数
	private String code="";
	
	private String usermail;
	private UserTB user;
	
	//传出参数
	private  Map<String,DictionaryTB> limitMap;
	private String access_token = "";
	private String expires_in = "";
	private String openid = "";
	private String userInfoJSONStr = "";
	private String client_id = "";
	
	
	
	
	private JSONObject userInfojson;
	
	StringBuffer setupStr1 = new  StringBuffer();
	StringBuffer setupStr2 = new  StringBuffer();
	StringBuffer setupStr3 = new  StringBuffer();
	
	
	//用户信息.
	private String ret = "";
	private String msg = "";
	private String nickname = "";
	private String figureurl = "";
	private String figureurl_1 = "";
	private String figureurl_2 = "";
	private String gender = "";
	
	
	public Map<String, DictionaryTB> getLimitMap() {
		return limitMap;
	}


	public void setLimitMap(Map<String, DictionaryTB> limitMap) {
		this.limitMap = limitMap;
	}


	public UserTB getUser() {
		return user;
	}


	public void setUser(UserTB user) {
		this.user = user;
	}


	public String getUsermail() {
		return usermail;
	}


	public void setUsermail(String usermail) {
		this.usermail = usermail;
	}


	public String execute(){
		/*BusiDatabaseManager databaseConnection = new BusiDatabaseManager();
		Connection conn = databaseConnection.getConnection();
		
		//UserTB user = session.get("userInfo");
		
		
		
		
		UserOS userOS = new UserOS(conn);
		if(usermail != null){
			user = userOS.getUserInfoByEmail(usermail);
		}else{
			user = (UserTB) session.get("userInfo");
		}
		
		
		DictionaryOS dictionaryOS = new DictionaryOS(conn);
		limitMap = dictionaryOS.getDictionaryLimitMap();
		
	r	databaseConnection.releaseConnection(conn);
		if(user == null)
		{
			return ERROR;
		}
		//*/
		try {
			getQQInfo();
			QQOperatorOS qqOperatorOS = new QQOperatorOS();
			OperatorOS operatorOS = new OperatorOS(qqOperatorOS.getConn());

			if(qqOperatorOS.isRealAccessTokenNOpenid(access_token,openid)){   //如果 access_token已经录入
				QQOperatorTB qqOperator = new QQOperatorTB();
				qqOperator = qqOperatorOS.getInfoByAccessToken(access_token);
				OperatorTB operator = operatorOS.getInfoByEmail(qqOperator.getEmail());
				OperatorlimitedOS userlimitedOS = new OperatorlimitedOS(operatorOS.getConn());
				
				OperatorLoginLogOS operatorLoginLogOS = new OperatorLoginLogOS();
				OperatorLoginLogTB operatorLastLoginLog = operatorLoginLogOS.getLastInfo(operator.getEmail_operator());
					
				Map<String,OperatorlimitedTB> operatorlimitedMap = userlimitedOS.getUserlimitedMap(operator);
				Map<String,List<LimitedTB>> operatorlimitedTree = userlimitedOS.getLimitedTree(operator);
				
				session.put("operatorLastLoginLog", operatorLastLoginLog);
				session.put("operatorInfo", operator);
				session.put("operatorlimitedMap", operatorlimitedMap);
				session.put("qqoperatorInfo", qqOperator);
				session.put("operatorlimitedTree", operatorlimitedTree);
				
				//写入登陆日志
				OperatorLoginLogTB operatorLoginLog = new OperatorLoginLogTB();
				operatorLoginLog.setType("QQ");
				operatorLoginLog.setAccount(operator.getEmail_operator());
				operatorLoginLog.setIp(request.getRemoteAddr());
				operatorLoginLog.setIswrong(false);
				operatorLoginLogOS.insert(operatorLoginLog);
				
				
				//考勤信息
				
				
				qqOperatorOS.releaseConnection();
				
				
			}else{   //如果未录入重新绑定
				
				session.put("access_token", access_token);
				session.put("openid", openid);
				
				
				qqOperatorOS.releaseConnection();
				return NONE;
			}
			
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return SUCCESS;
	}
	
	
	public String getQQInfo() throws JSONException{
		try {
			URL url= new URL("https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=100231532&client_secret=7e553a946bea3ff594ea3392adfa69e7&redirect_uri=www.zozopo.com&code="+code);
			//access_token=91C1291E02D224240AC21725348F53A0&expires_in=7776000
						
			HttpURLConnection urlconn;
			InputStream stream;

			urlconn = (HttpURLConnection) url.openConnection();
			
			urlconn.connect();
			stream = urlconn.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
			
			String temp ="";
			while((temp = reader.readLine()) != null){
				setupStr1.append(temp+"\n");
			} 
			String[] strArry = setupStr1.toString().split("&");
			String[] strArry2 = strArry[0].split("=");
			access_token = strArry2[1];
			
			urlconn.disconnect();
			stream.close();
			reader.close();
			
			//setupStr1.append(" URL:" +url + " access_token:" + access_token);
			
			//第二步.
			String setup1 = "https://graph.qq.com/oauth2.0/me?access_token="+access_token;
			//callback( {"client_id":"100231532","openid":"BBCE43A56DC0F1AF2FB407518A4F1240"} ); 
			URL url2= new URL(setup1);
			
			HttpURLConnection urlconn2 = (HttpURLConnection) url2.openConnection();
			urlconn2.connect();
			stream = urlconn2.getInputStream();
			reader = new BufferedReader(new InputStreamReader(stream));
			
			String temp2 ="";
			while((temp2 = reader.readLine()) != null){
				setupStr2.append(temp2+"\n");
			}
			
			urlconn2.disconnect();
			stream.close();
			reader.close();
			
			
			String setupStr = setupStr2.toString();
			setupStr =  setupStr.substring(setupStr.indexOf("(")+1);
			setupStr = setupStr.substring(0, setupStr.indexOf(")"));
			
			JSONObject jsonStr = new JSONObject(setupStr);
			
			client_id = jsonStr.get("client_id").toString();
			openid = jsonStr.get("openid").toString();
			
			
			
			
			//第三步.
			String setup2 ="https://graph.qq.com/user/get_user_info?access_token="+access_token+"&oauth_consumer_key=100231532&openid="+openid;  
			//{ "ret":0, "msg":"", "nickname":"啊编先生", "figureurl":"http://qzapp.qlogo.cn/qzapp/100231532/BBCE43A56DC0F1AF2FB407518A4F1240/30", "figureurl_1":"http://qzapp.qlogo.cn/qzapp/100231532/BBCE43A56DC0F1AF2FB407518A4F1240/50", "figureurl_2":"http://qzapp.qlogo.cn/qzapp/100231532/BBCE43A56DC0F1AF2FB407518A4F1240/100", "gender":"男" } 
			
			URL url3= new URL(setup2);
			HttpURLConnection urlconn3 = (HttpURLConnection) url3.openConnection();
			urlconn3.connect();
			stream = urlconn3.getInputStream();
			reader = new BufferedReader(new InputStreamReader(stream,"UTF-8"));
			
			
			String temp3 ="";
			while((temp3 = reader.readLine()) != null){
				setupStr3.append(temp3+"\n");
			}
			
			urlconn3.disconnect();
			stream.close();
			reader.close();
			
			userInfojson= new JSONObject(setupStr3.toString());
			
			ret = userInfojson.get("ret").toString();
			msg = userInfojson.get("msg").toString();
			nickname = userInfojson.get("nickname").toString();
			figureurl = userInfojson.get("figureurl").toString();
			figureurl_1 = userInfojson.get("figureurl_1").toString();
			figureurl_2 = userInfojson.get("figureurl_2").toString();
			gender = userInfojson.get("gender").toString();
			
			userInfoJSONStr = userInfojson.toString();
			//*/
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "";
	}
	

	public String getQQInfoTest() throws JSONException{
		
			//access_token=91C1291E02D224240AC21725348F53A0&expires_in=7776000
		
			setupStr1.append("access_token=91C1291E02D224240AC21725348F53A0&expires_in=7776000");
			
			String[] strArry = setupStr1.toString().split("&");
			String[] strArry2 = strArry[0].split("=");
			access_token = strArry2[1];
			//setupStr1.append(" URL:" +url + " access_token:" + access_token);
			
			//第二步.
			setupStr2.append("callback( {\"client_id\":\"100231532\",\"openid\":\"BBCE43A56DC0F1AF2FB407518A4F1240\"} );");
			String setupStr = setupStr2.toString();
			setupStr =  setupStr.substring(setupStr.indexOf("(")+1);
			setupStr = setupStr.substring(0, setupStr.indexOf(")"));
			
			JSONObject jsonStr = new JSONObject(setupStr);
			
			client_id = jsonStr.get("client_id").toString();
			openid = jsonStr.get("openid").toString();
			//第三步.
			//{ "ret":0, "msg":"", "nickname":"啊编先生", "figureurl":"http://qzapp.qlogo.cn/qzapp/100231532/BBCE43A56DC0F1AF2FB407518A4F1240/30", "figureurl_1":"http://qzapp.qlogo.cn/qzapp/100231532/BBCE43A56DC0F1AF2FB407518A4F1240/50", "figureurl_2":"http://qzapp.qlogo.cn/qzapp/100231532/BBCE43A56DC0F1AF2FB407518A4F1240/100", "gender":"男" } 

			setupStr3.append("{ \"ret\":0, \"msg\":\"\", \"nickname\":\"啊编先生\", \"figureurl\":\"http://qzapp.qlogo.cn/qzapp/100231532/BBCE43A56DC0F1AF2FB407518A4F1240/30\", \"figureurl_1\":" +
					"\"http://qzapp.qlogo.cn/qzapp/100231532/BBCE43A56DC0F1AF2FB407518A4F1240/50\"," +
					" \"figureurl_2\":\"http://qzapp.qlogo.cn/qzapp/100231532/BBCE43A56DC0F1AF2FB407518A4F1240/100\", \"gender\":\"男\" } ");
		
			
			userInfojson= new JSONObject(setupStr3.toString());
			
			ret = userInfojson.get("ret").toString();
			msg = userInfojson.get("msg").toString();
			nickname = userInfojson.get("nickname").toString();
			figureurl = userInfojson.get("figureurl").toString();
			figureurl_1 = userInfojson.get("figureurl_1").toString();
			figureurl_2 = userInfojson.get("figureurl_2").toString();
			gender = userInfojson.get("gender").toString();
			
			userInfoJSONStr = userInfojson.toString();
			//*/
	
		
		return "";
	}

	public void setServletRequest(HttpServletRequest arg0) {
		// TODO Auto-generated method stub
		request = arg0;
	}

	public void setSession(Map arg0) {
		// TODO Auto-generated method stub
		session = arg0;
	}

	public void setServletResponse(HttpServletResponse arg0) {
		// TODO Auto-generated method stub
		response = arg0;
		response.setCharacterEncoding("GB2312");
		response.setContentType("text/xml; charset=gb2312");
	}


	public String getCode() {
		return code;
	}


	public void setCode(String code) {
		this.code = code;
	}


	public String getAccess_token() {
		return access_token;
	}


	public void setAccess_token(String access_token) {
		this.access_token = access_token;
	}


	public String getExpires_in() {
		return expires_in;
	}


	public void setExpires_in(String expires_in) {
		this.expires_in = expires_in;
	}


	public String getOpenid() {
		return openid;
	}


	public void setOpenid(String openid) {
		this.openid = openid;
	}





	public StringBuffer getSetupStr1() {
		return setupStr1;
	}


	public void setSetupStr1(StringBuffer setupStr1) {
		this.setupStr1 = setupStr1;
	}


	public StringBuffer getSetupStr2() {
		return setupStr2;
	}


	public void setSetupStr2(StringBuffer setupStr2) {
		this.setupStr2 = setupStr2;
	}


	public StringBuffer getSetupStr3() {
		return setupStr3;
	}


	public void setSetupStr3(StringBuffer setupStr3) {
		this.setupStr3 = setupStr3;
	}


	public String getClient_id() {
		return client_id;
	}


	public void setClient_id(String client_id) {
		this.client_id = client_id;
	}


	public JSONObject getUserInfojson() {
		return userInfojson;
	}


	public void setUserInfojson(JSONObject userInfojson) {
		this.userInfojson = userInfojson;
	}


	public String getUserInfoJSONStr() {
		return userInfoJSONStr;
	}


	public void setUserInfoJSONStr(String userInfoJSONStr) {
		this.userInfoJSONStr = userInfoJSONStr;
	}


	public String getRet() {
		return ret;
	}


	public void setRet(String ret) {
		this.ret = ret;
	}


	public String getMsg() {
		return msg;
	}


	public void setMsg(String msg) {
		this.msg = msg;
	}


	public String getNickname() {
		return nickname;
	}


	public void setNickname(String nickname) {
		this.nickname = nickname;
	}


	public String getFigureurl() {
		return figureurl;
	}


	public void setFigureurl(String figureurl) {
		this.figureurl = figureurl;
	}


	public String getFigureurl_1() {
		return figureurl_1;
	}


	public void setFigureurl_1(String figureurl_1) {
		this.figureurl_1 = figureurl_1;
	}


	public String getFigureurl_2() {
		return figureurl_2;
	}


	public void setFigureurl_2(String figureurl_2) {
		this.figureurl_2 = figureurl_2;
	}


	public String getGender() {
		return gender;
	}


	public void setGender(String gender) {
		this.gender = gender;
	}
}
